﻿using System;
using AbpProjectTemplate.Web.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace AbpProjectTemplate.Web.Authentication
{
    public static class AuthAspNetCoreExtensions
    {
        /// <summary>
        /// 添加系统认证
        /// </summary>
        public static void AddAppAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            var jwtOpts = new JwtAuthOptions(configuration);
            services.AddSingleton(jwtOpts);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Audience = jwtOpts.Audience;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = jwtOpts.SecurityKey,

                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer = jwtOpts.Issuer,

                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience = jwtOpts.Audience,

                    // Validate the token expiry
                    ValidateLifetime = true,

                    // If you want to allow a certain amount of clock drift, set that here
                    ClockSkew = TimeSpan.Zero,

                };
                options.Events = new AppJwtBearerEvents();
            });
        }
        /// <summary>
        /// 用户SecurityStamp验证
        /// </summary>
        public static IApplicationBuilder UseSecurityStampVerification(this IApplicationBuilder app)
        {
            return app.UseMiddleware<SecurityStampVerificationMiddleware>();
        }
    }
}


